import { Injectable, NestInterceptor, ExecutionContext, CallHandler, Logger } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { Request, Response } from 'express';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  private readonly logger = new Logger(LoggingInterceptor.name);

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const ctx = context.switchToHttp();
    const request = ctx.getRequest<Request>();
    const response = ctx.getResponse<Response>();
    const startTime = Date.now();

    return next.handle().pipe(
      tap(() => {
        const endTime = Date.now();
        const duration = endTime - startTime;

        this.logger.log(
          `请求路径: ${request.url} - 方法: ${request.method} - IP: ${request.ip} - 状态: ${response.statusCode} - 耗时: ${duration}ms`,
        );

        if (request.body && Object.keys(request.body).length > 0) {
          this.logger.debug(`请求参数: ${JSON.stringify(request.body)}`);
        }
      }),
    );
  }
}